import os
import argparse

from .utils import src_dir

_args = None

def get():
    if not _args:
        raise Exception("Arguments are not initialized. Call initialize() first.")
    return _args


def init(argv=None):
    """Initializes the argument registry. If no argv is supplied (default), 
    parses arguments from process command line.
    The initialization result will be kept in the module-level member `_args`,
    so that the settings can be retrieved from other modules with get().
    """
    global _args

    _src_dir = src_dir()
    parser = argparse.ArgumentParser(description="Molecular Simulation for DL.")
    parser.add_argument(
        "--base-dir",
        type=str,
        default=os.getcwd(),
        help="A directory for running simulation",
    )
    parser.add_argument(
        "--log-dir",
        type=str,
        default=None,
        help="A directory for saving results",
    )
    parser.add_argument(
        "--prot-file",
        type=str,
        required=True,
        help="Protein file for simulation",
    )
    parser.add_argument(
        "--temp-k",
        type=int,
        default=300,
        help="Simulation temperature in Kelvin",
    )
    parser.add_argument(
        "--max-cyc",
        type=int,
        default=100,
        help="Maximum energy minimization cycles in preprocessing",
    )
    parser.add_argument(
        "-v",
        "--verbose",
        action='count',
        default=0,
        help="""Verbosity level"""
    )

    _args = parser.parse_args(argv)
    _args.prot_name = os.path.basename(_args.prot_file)[:-4]
    if _args.log_dir is None:
        _args.log_dir = os.path.join(_args.base_dir, f"Logs-{_args.prot_name}")
    os.makedirs(_args.log_dir, exist_ok=True)
    _args.base_dir = os.path.abspath(_args.base_dir)
    _args.log_dir = os.path.abspath(_args.log_dir)
    _args.prot_file = os.path.abspath(_args.prot_file)
    _args.utils_dir = os.path.join(_src_dir, "utils")

    return _args